import os.path

from PyQt5.QtCore import *
from PyQt5.QtGui import QImage, QPixmap, QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import *
from UI.CountBug import *
from openpyxl import load_workbook, Workbook


class MainWidow(QMainWindow):

    def __init__(self, name='Dlg'):
        super().__init__()
        self.model = QStandardItemModel(10, 4)
        self.ui = Ui_MainWindow()
        self.init_ui(name)

        pass

    def init_ui(self, name):
        self.ui.setupUi(self)
        self.setWindowTitle(name)
        self.init_tableview()
        self.init_connect()

    def init_tableview(self):
        self.model.beginResetModel()
        self.model.endResetModel()
        self.model.setHorizontalHeaderLabels(['问题重要度', 'Bug状态', '数量', ''])
        self.ui.tableView.setModel(self.model)

    def init_connect(self):
        self.ui.pushButton_select.clicked.connect(self.select_btn_clicked)
        self.ui.pushButton_count.clicked.connect(self.count_btn_clicked)
        self.ui.pushButton_clear.clicked.connect(self.clear_btn_clicked)
        pass

    def clear_btn_clicked(self):
        self.model.clear()
        self.ui.lineEdit.setText("")
        pass

    def select_btn_clicked(self):
        filename, filetype = QFileDialog.getOpenFileName(self, "选择文件", "./", "All File(*);;Excel Files(*.xlsx)")
        print(filetype, filename)
        self.ui.lineEdit.setText(filename)
        pass

    def count_btn_clicked(self):
        if len(self.ui.lineEdit.text()) == 0:
            QMessageBox.warning(self, '警告','没有选择文件')
        else:
            dict_p, num = self.count_bug()
            if len(dict_p) == 0:
                QMessageBox.warning(self, '警告', '文件中没有数据或读取文件失败')
            else:
                self.show_tableview(dict_p, num)
                self.save_excel(dict_p, num)
        pass

    def save_excel(self, dict_p: dict, num: int):
        cur_dir = os.path.dirname(self.ui.lineEdit.text())
        file = os.path.join(cur_dir, 'CountResult.xlsx')
        print(file)
        wb = Workbook()
        wb.create_sheet('count', 0)
        sheet = wb.get_sheet_by_name('count')
        row_index = 1
        col_index = 1
        for key in dict_p.keys():
            sheet.cell(row_index, col_index).value = key
            col_index += 1
            for key_s in dict_p[key].keys():
                sheet.cell(row_index, col_index).value = key_s
                col_index += 1
                dict_temp = dict_p[key]
                sheet.cell(row_index, col_index).value = dict_temp[key_s]
                # item = QStandardItem(str(dict_temp[key_s]))
                # self.model.setItem(row_index, col_index, item)
                print('row = %d, col = %d, item = %d', row_index, col_index, dict_temp[key_s])
                row_index += 1
                col_index = 2
            col_index = 1
        sheet.cell(row_index, col_index).value = '总计'
        col_index += 2
        sheet.cell(row_index, col_index).value = num
        wb.save(file)

    def show_tableview(self, dict_p: dict, num: int):
        row_index = 0
        col_index = 0
        for key in dict_p.keys():
            item = QStandardItem(key)
            self.model.setItem(row_index, col_index, item)
            col_index += 1
            for key_s in dict_p[key].keys():
                item = QStandardItem(key_s)
                self.model.setItem(row_index, col_index, item)
                col_index += 1
                dict_temp = dict_p[key]
                item = QStandardItem(str(dict_temp[key_s]))
                self.model.setItem(row_index, col_index, item)
                print('row = %d, col = %d, item = %d', row_index, col_index, dict_temp[key_s])
                row_index += 1
                col_index = 1
            col_index = 0
        item = QStandardItem('总计')
        self.model.setItem(row_index, col_index, item)
        item = QStandardItem(str(num))
        self.model.setItem(row_index, col_index+2, item)

    def invalid_file(self, wb) -> [int, int]:
        sheets = wb.get_sheet_names()
        b_exit = False
        for sheet in sheets:
            if sheet == '问题汇总':
                b_exit = True
                break
        if not b_exit:
            QMessageBox.warning(self, '警告', '文件中不存在_问题汇总_')
            return 0, 0
        sheet = wb.get_sheet_by_name('问题汇总')
        severity_index = 1
        status_index = 1
        index = 1
        while index <= sheet.max_column:
            if sheet.cell(row=1, column=index).value == '问题重要度':
                severity_index = index
            elif sheet.cell(row=1, column=index).value == 'Bug状态':
                status_index = index
            index = index + 1
        if index == 1:
            QMessageBox.warning(self, '警告', '缺少列')
        elif severity_index == 1:
            QMessageBox.warning(self, '警告', '缺少列-问题重要度')
        elif status_index == 1:
            QMessageBox.warning(self, '警告', '缺少列-Bug状态')
        return severity_index, status_index

    def count_bug(self) -> [dict, int]:
        file = self.ui.lineEdit.text()
        wb = load_workbook(file)
        severity_index, status_index = self.invalid_file(wb)
        if severity_index == 0 and status_index == 0:
            return {}, 0
        sheet = wb.get_sheet_by_name('问题汇总')
        # count
        row_index = 1
        row_max = sheet.max_row
        dict_status_p0 = {}
        dict_status_p1 = {}
        dict_status_p2 = {}
        dict_status_p3 = {}
        dict_severity = {}
        p0_close_num = p0_all_num = p1_close_num = p1_all_num = p2_close_num = p2_all_num = p3_close_num = p3_all_num = 0
        while row_index <= row_max:
            if sheet.cell(row=row_index, column=severity_index).value == 'P0':
                p0_all_num += 1
                if sheet.cell(row=row_index, column=status_index).value == '已关闭':
                    p0_close_num += 1
            elif sheet.cell(row=row_index, column=severity_index).value == 'P1':
                p1_all_num += 1
                if sheet.cell(row=row_index, column=status_index).value == '已关闭':
                    p1_close_num += 1
            elif sheet.cell(row=row_index, column=severity_index).value == 'P2':
                p2_all_num += 1
                if sheet.cell(row=row_index, column=status_index).value == '已关闭':
                    p2_close_num += 1
            elif sheet.cell(row=row_index, column=severity_index).value == 'P3':
                p3_all_num += 1
                if sheet.cell(row=row_index, column=status_index).value == '已关闭':
                    p3_close_num += 1
            row_index += 1

        dict_status_p0['总数'] = p0_all_num
        dict_status_p0['已关闭'] = p0_close_num
        dict_severity['P0'] = dict_status_p0
        dict_status_p1['总数'] = p1_all_num
        dict_status_p1['已关闭'] = p1_close_num
        dict_severity['P1'] = dict_status_p1
        dict_status_p2['总数'] = p2_all_num
        dict_status_p2['已关闭'] = p2_close_num
        dict_severity['P2'] = dict_status_p2
        dict_status_p3['总数'] = p3_all_num
        dict_status_p3['已关闭'] = p3_close_num
        dict_severity['P3'] = dict_status_p3

        print(dict_severity)
        wb.close()
        return dict_severity, p0_all_num + p1_all_num + p2_all_num + p3_all_num

